<template>
	<view class="container">
		<!-- 页面顶部 -->
		<view v-if="list.length" class="head-info">
			<view class="cart-total">
				<text>共</text>
				<text class="active">{{ total }}</text>
				<text>件商品</text>
			</view>
			<view class="cart-edit" @click="handleToggleMode()">
				<view v-if="mode == 'normal'" class="normal">
					<text class="icon iconfont icon-bianji"></text>
					<text>管理</text>
				</view>
				<view v-if="mode == 'edit'" class="edit">
					<text>完成</text>
				</view>
			</view>
		</view>
		<!-- 购物车商品列表 -->
		<view v-if="list.length" class="cart-list">
			<view class="cart-item" v-for="(item, index) in list" :key="index">
				<view class="item-radio" @click="handleCheckItem(item.skuId)">
					<uLCheckbox :modelValue="inArray(item.skuId, checkedIds)" shape="circle" activeColor="#FF0000" />
				</view>
				<view class="goods-image" @click="onTargetGoods(item)">
					<image class="image" :src="item.pic
						? (item.pic.startsWith('https')
							? item.pic
							: 'https://saas.hzjhckj.com/api' + item.pic)
						: 'https://building-d.oss-cn-hangzhou.aliyuncs.com/img/img.jpg'" mode="scaleToFill"></image>
				</view>
				<view class="item-content">
					<view class="goods-title" @click="onTargetGoods(item)">
						<text class="twoline-hide">{{ item.name }}</text>
					</view>
					<view class="skuType">
						<view class="spec-list">
				<view
					v-for="(v,i) in item.specification" :key="i">
					{{v.key}}:
					{{v.value}}
				</view>

			</view>
					</view>
					<view class="item-foot">
						<view class="goods-price">
							<text class="unit">￥</text>
							<text class="value">{{ item.price }}</text>
						</view>
						<view class="stepper">
							<u-number-box v-model="item.num" :disabled="mode == 'normal'" :step="1" min="1" max="20"
								button-size="20" bgColor="#FF0000" color="#ffffff"
								@change="onChangeStepper($event, item)" />
						</view>
					</view>
				</view>
			</view>
		</view>
		<u-empty v-if="list.length == 0" mode="car" icon="http://cdn.uviewui.com/uview/empty/car.png">
		</u-empty>
		<!-- 失效商品 -->
		<view v-if="offLinelist.length" class="head-info">
			<view class="cart-total">
				<text>失效商品</text>
				<text class="active">{{ offLinelist.length }}</text>
				<text>件</text>
			</view>
		</view>

		<view v-if="offLinelist.length" class="cart-list lose">
			<view class="cart-item" v-for="(item, index) in offLinelist" :key="index">
				<view class="item-radio" @click="handleCheckItem(item.skuId)">
					<uLCheckbox :modelValue="inArray(item.skuId, checkedIds)" shape="circle" activeColor="#FF0000" />
				</view>
				<view class="goods-image" @click="onTargetGoods(item)">
					<image class="image" :src="item.pic
						? (item.pic.startsWith('https')
							? item.pic
							: 'https://saas.hzjhckj.com/api' + item.pic)
						: 'https://building-d.oss-cn-hangzhou.aliyuncs.com/img/img.jpg'" mode="scaleToFill"></image>
				</view>
				<view class="loseContent">
					<view class="goods-title" @click="onTargetGoods(item)">
						<text class="twoline-hide">{{ item.name }}</text>
					</view>
					<view class="loseText">
						该商品已下架，暂不能购买
					</view>
				</view>
			</view>
		</view>
		<!-- 底部操作栏 -->
		<view v-if="list.length" class="footer-fixed">
			<view class="all-radio">
				<uLCheckbox :modelValue="checkedIds.length > 0 && checkedIds.length === list.length" shape="circle"
					activeColor="#FF0000" @change="handleCheckAll()">全选</uLCheckbox>
			</view>
			<view class="total-info">
				<text>合计：</text>
				<view class="goods-price">
					<text class="unit">￥</text>
					<text class="value">{{ totalPrice }}</text>
				</view>
			</view>
			<view class="cart-action">
				<view class="btn-wrapper">
					<!-- dev:下面的disabled条件使用checkedIds.join方式判断 -->
					<!-- dev:通常情况下vue项目使用checkedIds.length更合理, 但是length属性在微信小程序中不起作用 -->
					<view v-if="mode == 'normal'" class="btn-item btn-main"
						:class="{ disabled: checkedIds.join() == '' }" @click="handleOrder()">
						<text>去支付 {{ checkedIds.length > 0 ? `(${total})` : '' }}</text>
					</view>
					<view v-if="mode == 'edit'" class="btn-item btn-main" :class="{ disabled: !checkedIds.length }"
						@click="handleDelete()">
						<text>删除</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getCarList,
		carEdit,
		carDelete
	} from '@/api/car.js'
	import {
		inArray,
		arrayIntersect,
		debounce
	} from '@/utils/util'
	import uLCheckbox from './u-checkbox'

	const CartIdsIndex = 'CartIds'

	export default {
		data() {
			return {
				inArray,
				// 正在加载
				isLoading: true,
				// 当前模式: normal正常 edit编辑
				mode: 'normal',
				// 购物车商品列表
				list: [],
				// 购物车商品总数量
				total: null,
				// 选中的商品ID记录
				checkedIds: [],
				// 选中的商品总金额
				totalPrice: '0.00',
				allValue: '',
				offLinelist: []
			}
		},
		components: {
			uLCheckbox
		},
		watch: {
			// 监听选中的商品
			checkedIds: {
				handler(val) {
					// 计算合计金额
					this.onCalcTotalPrice()
					// 记录到缓存中
					uni.setStorageSync(CartIdsIndex, val)
				},
				deep: true,
				immediate: false
			},
			// 监听购物车商品总数量
			total(val) {
				// 缓存并设置角标
				// setCartTotalNum(val)
				// setCartTabBadge()
			}
		},

		/**
		 * 生命周期函数--监听页面显示
		 */
		onShow(options) {
			// 获取缓存中的选中记录
			// this.checkedIds = uni.getStorageSync(CartIdsIndex)
			// 获取购物车商品列表
			// checkLogin() ? this.getCartList() : this.isLoading = false
			this.getCartList()
			uni.removeStorageSync("detail1");
		},

		methods: {
			// 计算合计金额 (根据选中的商品)
			onCalcTotalPrice() {

				const app = this
				// 选中的商品记录
				const checkedList = app.list.filter(item => inArray(item.skuId, app.checkedIds))
				// 计算总金额
				let tempPrice = 0;
				console.log(checkedList)
				checkedList.forEach(item => {
					// 商品单价, 为了方便计算先转换单位为分 (整数)
					const unitPrice = item.price * 100
					tempPrice += unitPrice * item.num
				})
				app.totalPrice = (tempPrice / 100).toFixed(2)
			},

			// 获取购物车商品列表
			async getCartList() {
				const res = await getCarList()
				this.offLinelist = res.offLinelist // 失效商品
				this.list = res.onLinelist.map(item => {
					item.specification = (JSON.parse(item.specification))
					return item
				})
				this.total = res.onLinelist.length
				this.onClearInvalidId()
				this.isLoading = false
				// const app = this
				// app.isLoading = true
				// CartApi.list()
				// 	.then(result => {
				// 		app.list = result.data.list
				// 		app.total = result.data.cartTotal
				// 		// 清除checkedIds中无效的ID
				// 		
				// 	})
				// 	.finally(() => app.isLoading = false)
			},

			// 清除checkedIds中无效的ID
			onClearInvalidId() {
				const app = this
				const listIds = app.list.map(item => item.skuId)
				app.checkedIds = arrayIntersect(listIds, app.checkedIds)
			},

			// 切换当前模式
			async handleToggleMode() {
				if (this.mode == 'edit') {
					console.log(1)
					var list = this.list.map(item => {
						return {
							skuId: item.skuId,
							num: item.num,
						}
					})
					const res = await carEdit({
						list
					})
					uni.showToast({
						title: '成功'
					})
				}
				this.mode = this.mode == 'normal' ? 'edit' : 'normal'

			},

			// 监听步进器更改事件
			onChangeStepper({
				value
			}, item) {
				// 这里是组织首次启动时的执行
				if (item.num == value) return
				// 记录一个节流函数句柄
				if (!item.debounceHandle) {
					item.oldValue = item.num
					item.debounceHandle = debounce(this.onUpdateCartNum, 500)
				}
				// 更新商品数量
				item.num = value
				// 提交更新购物车数量 (节流)
				item.debounceHandle(item, item.oldValue, value)
			},

			// 提交更新购物车数量
			async onUpdateCartNum(item, oldValue, newValue) {
				// 重新计算合计金额
				this.onCalcTotalPrice()
				// 清除节流函数句柄
				item.debounceHandle = null
			},

			// 跳转到商品详情页
			onTargetGoods(item) {
				// .skuId, item.productId
				this.$navTo('pages/goods/detail', {
					// goodsId: item.skuId,
					productId: item.productId
				})
			},

			// 选中商品
			handleCheckItem(cartId) {
				console.log(cartId)
				const {
					checkedIds
				} = this
				console.log(checkedIds)
				const index = checkedIds.findIndex(id => id === cartId)
				index < 0 ? checkedIds.push(cartId) : checkedIds.splice(index, 1)
			},

			// 全选事件
			handleCheckAll() {
				const {
					checkedIds,
					list
				} = this
				this.checkedIds = checkedIds.length === list.length ? [] : list.map(item => item.skuId)
			},

			// 结算选中的商品
			handleOrder() {
				const app = this
				if (app.checkedIds.length) {
					const cartIds = app.checkedIds.join()
					uni.navigateTo({
						url: `/pages/checkout/index?cartIds=${cartIds}&type=2`
					})
				}
			},

			// 删除选中的商品弹窗事件
			handleDelete() {
				const app = this
				if (!app.checkedIds.length) {
					return false
				}
				uni.showModal({
					title: '友情提示',
					content: '您确定要删除该商品吗？',
					showCancel: true,
					success({
						confirm
					}) {
						// 确认删除
						confirm && app.onClearCart()
					}
				})
			},

			// 确认删除商品
			async onClearCart() {
				this.list = this.list.filter(item => !this.checkedIds.includes(item.skuId));
				this.offLinelist = this.offLinelist.filter(item => !this.checkedIds.includes(item.skuId));
				// 重新计算合计金额
				this.onCalcTotalPrice()
				await carDelete({
					skuIds: this.checkedIds
				})
				this.getCartList()
				this.handleToggleMode()
			}

		}
	}
</script>

<style>
	page {
		background: #f5f5f5;
	}
</style>
<style lang="scss" scoped>
	.container {
		padding-bottom: 120rpx;
	}

	// 失效
	.lose {
		.loseContent {
			height: 200rpx;
			flex: 1;
			padding: 15rpx 0 15rpx 24rpx;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			justify-content: space-between;
			color: #999;
		}

		.loseText {
			font-size: 26rpx;

		}
	}

	// 页面顶部
	.head-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 4rpx 30rpx;
		// background-color: #fff;
		height: 60rpx;

		.cart-total {
			font-size: 28rpx;
			color: #333;

			.active {
				color: #007aff;
				margin: 0 2rpx;
			}
		}

		.cart-edit {
			padding-left: 20rpx;

			.icon {
				margin-right: 12rpx;
			}

			.edit {
				color: #FF0000;
			}
		}

	}

	// 购物车列表
	.cart-list {
		padding: 0 16rpx 0 16rpx;
	}

	.cart-item {
		background: #fff;
		border-radius: 12rpx;
		display: flex;
		align-items: center;
		padding: 30rpx 16rpx;
		margin-bottom: 24rpx;

		.item-radio {
			width: 56rpx;
			height: 80rpx;
			margin-right: 10rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}

		.goods-image {
			width: 200rpx;
			height: 200rpx;

			.image {
				display: block;
				width: 100%;
				height: 100%;
				border-radius: 8rpx;
			}
		}

		.item-content {
			flex: 1;
			padding-left: 24rpx;

			.goods-title {
				font-size: 28rpx;
				max-height: 76rpx;
			}

			.skuType {
				margin-right: 15rpx;
				padding: 5rpx 0;
				border: 1rpx solid transparent;
				border-radius: 8rpx;
				margin-top: 10rpx;
				font-size: 24rpx;
			}

			.item-foot {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 20rpx;

				.goods-price {
					vertical-align: bottom;
					color: #FF0000;

					.unit {
						font-size: 24rpx;
					}

					.value {
						font-size: 32rpx;
					}
				}
			}

		}
	}



	// 底部操作栏
	.footer-fixed {
		display: flex;
		align-items: center;
		height: 96rpx;
		background: #fff;
		padding: 0 30rpx;
		position: fixed;
		bottom: var(--window-bottom);
		left: 0;
		right: 0;
		z-index: 11;

		.all-radio {
			width: 140rpx;
			display: flex;
			align-items: center;

			.radio {
				margin-bottom: -4rpx;
				transform: scale(0.76)
			}
		}

		.total-info {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			padding-right: 30rpx;

			.goods-price {
				vertical-align: bottom;
				color: #FF0000;

				.unit {
					font-size: 24rpx;
				}

				.value {
					font-size: 32rpx;
				}
			}
		}

		.cart-action {
			width: 200rpx;

			.btn-wrapper {
				height: 100%;
				display: flex;
				align-items: center;
			}

			.btn-item {
				flex: 1;
				font-size: 28rpx;
				height: 72rpx;
				color: #fff;
				border-radius: 50rpx;
				display: flex;
				justify-content: center;
				align-items: center;
			}

			// 去结算按钮
			.btn-main {
				background: #FF0000;
				color: #ffffff;

				// 禁用按钮
				&.disabled {
					opacity: 0.6;
				}
			}

		}

	}
</style>